<!--
*Author：COCO
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *业务请在@/extension/new_qualitytest/inboundtest/Quality_InboundTest.js此处编写
 -->
<template>
  <div class="inspection-container">
    <div class="form-container">
      <!-- 基础信息 -->
      <div class="section-title">基础信息</div>
      <div class="form-section">
        <div class="form-row">
          <div class="form-item">
            <span class="label">检验主题</span>
            <el-input v-model="editFormFields.InspectionSubject" placeholder="请输入检验主题"></el-input>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item required">
            <span class="label">检验单号</span>
            <el-input v-model="editFormFields.InspectionOrderCode" placeholder="JYDH2022060608340781361">
              <template #append>
                <el-checkbox v-model="autoGenerateCode">自动编号</el-checkbox>
              </template>
            </el-input>
          </div>
          <div class="form-item required">
            <span class="label">检验日期</span>
            <el-date-picker v-model="editFormFields.InspectionDate" type="date" placeholder="选择日期" />
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <span class="label">检验人员</span>
            <el-select v-model="editFormFields.Inspector" filterable remote placeholder="请选择人员">
              <el-option label="测试人员" value="测试人员"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <span class="label">所在部门</span>
            <el-select v-model="editFormFields.Department" filterable remote placeholder="请选择">
              <el-option label="测试部门" value="测试部门"></el-option>
            </el-select>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <span class="label">联系方式</span>
            <el-input v-model="editFormFields.ContactPhone" placeholder="请输入"></el-input>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item-full">
            <span class="label">备注</span>
            <el-input v-model="editFormFields.InspectorRemark" type="textarea" :rows="4" placeholder="请输入备注"></el-input>
          </div>
        </div>
      </div>

      <!-- 采购信息 -->
      <div class="section-title">采购信息</div>
      <div class="form-section">
        <div class="form-row">
          <div class="form-item">
            <span class="label">采购单号</span>
            <el-input v-model="purchaseInfo.purchaseOrderCode" placeholder="请选择采购单号" readonly @click="openPurchaseOrderDialog">
              <template #append>
                <el-button @click="openPurchaseOrderDialog"><i class="el-icon-search"></i></el-button>
              </template>
            </el-input>
          </div>
          <div class="form-item">
            <span class="label">采购日期</span>
            <el-date-picker v-model="purchaseInfo.purchaseDate" type="date" placeholder="选择日期" disabled />
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <span class="label">供应商名称</span>
            <el-select v-model="purchaseInfo.supplierName" filterable disabled placeholder="请选择">
              <el-option label="测试供应商" value="测试供应商"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <span class="label">联系人</span>
            <el-input v-model="purchaseInfo.contactPerson" placeholder="请输入" disabled></el-input>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <span class="label">联系电话</span>
            <el-input v-model="purchaseInfo.supplierPhone" placeholder="请输入" disabled></el-input>
          </div>
          <div class="form-item">
            <span class="label">采购人员</span>
            <el-select v-model="purchaseInfo.purchaser" filterable disabled placeholder="请选择">
              <el-option label="测试采购员" value="测试采购员"></el-option>
            </el-select>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <span class="label">采购部门</span>
            <el-select v-model="purchaseInfo.purchaseDepartment" filterable disabled placeholder="请选择">
              <el-option label="测试部门" value="测试部门"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <span class="label">联系方式</span>
            <el-input v-model="purchaseInfo.purchaseContactPhone" placeholder="请输入" disabled></el-input>
          </div>
        </div>
      </div>

      <!-- 检验明细 -->
      <div class="inspection-detail-section">
        <div class="detail-header">
          <div>检验明细</div>
          <div class="detail-buttons">
            <el-button type="primary" size="small" @click="addDetail">添加</el-button>
            <el-button type="danger" size="small" @click="removeSelected">移除</el-button>
          </div>
        </div>
        <el-table :data="detailData" border style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="序号" width="60" type="index"></el-table-column>
          <el-table-column prop="materialId" label="物品ID" width="280"></el-table-column>
          <el-table-column prop="materialCode" label="物品编号" width="120"></el-table-column>
          <el-table-column prop="materialName" label="物品名称" width="120"></el-table-column>
          <el-table-column prop="modelNumber" label="规格型号" width="100"></el-table-column>
          <el-table-column prop="unit" label="单位" width="60"></el-table-column>
          <el-table-column prop="brand" label="品牌" width="100"></el-table-column>
          <el-table-column prop="purchaseQuantity" label="采购数量" width="100"></el-table-column>
          <el-table-column label="检验类型" width="100">
            <template #default="scope">
              <el-select v-model="scope.row.inspectionType" placeholder="请选择">
                <el-option label="免检" value="免检"></el-option>
                <el-option label="抽检" value="抽检"></el-option>
                <el-option label="全检" value="全检"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="收货数量" width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.receivedQuantity" placeholder="请输入" :min="0" :controls="false"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="检验数量" width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.inspectionQuantity" placeholder="请输入" :min="0" :controls="false"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="合格数量" width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.qualifiedQuantity" placeholder="请输入" :min="0" :controls="false"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="不良数量" width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.defectQuantity" placeholder="请输入" :min="0" :controls="false"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="入库数量" width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.warehouseQuantity" placeholder="请输入" :min="0" :controls="false"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="退货数量" width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.returnQuantity" placeholder="请输入" :min="0" :controls="false"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90" fixed="right">
            <template #default="scope">
              <el-button type="text" size="small" class="delete-btn" @click="removeDetail(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 附件 -->
      <div class="attachment-section">
        <div class="section-title">附件</div>
        <div class="upload-area">
          <div class="existing-file" v-if="attachment">
            <div class="file-info">
              <div>{{ attachment.name }}</div>
              <div class="file-meta">
                文件大小: {{ attachment.size }}
                <br>上传日期: {{ attachment.uploadDate }}
              </div>
            </div>
            <div class="file-actions">
              <el-button type="primary" size="small" @click="reuploadFile">重新上传</el-button>
              <el-button size="small" @click="deleteFile">删除</el-button>
            </div>
          </div>
          <div class="upload-box" v-else>
            <el-upload
              action="#"
              :auto-upload="false"
              drag
              :on-change="fileChange"
              :show-file-list="false"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">点击上传 / 拖拽到此区域</div>
              <template #tip>
                <div class="el-upload__tip">
                  支持任何类型文件，大小不超过50MB
                </div>
              </template>
            </el-upload>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" @click="saveWithAttachment">保存</el-button>
      </div>
    </div>

    <!-- 采购单号选择弹框 -->
    <el-dialog title="选择采购单" v-model="purchaseDialogVisible" width="70%">
      <div class="search-bar">
        <el-form :inline="true">
          <el-form-item label="采购单号">
            <el-input v-model="searchParams.purchaseOrderCode" placeholder="请输入采购单号"></el-input>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="searchParams.supplierId" placeholder="请选择供应商">
              <el-option label="测试供应商" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchPurchaseOrders">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="purchaseOrders" border style="width: 100%" @selection-change="handlePurchaseSelectionChange" highlight-current-row @row-click="handleRowClick" ref="purchaseTable">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column prop="purchaseOrderCode" label="采购单号" width="120"></el-table-column>
        <el-table-column prop="orderTitle" label="采购订单主题" width="180"></el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="150"></el-table-column>
        <el-table-column prop="purchaseDate" label="采购日期" width="120"></el-table-column>
        <el-table-column prop="itemSummary" label="物品概要" width="180"></el-table-column>
        <el-table-column prop="purchaser" label="采购人员" width="100"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectPurchase">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加明细选择弹窗 -->
    <el-dialog title="添加检验明细" v-model="detailDialogVisible" width="70%">
      <div class="search-bar">
        <el-form :inline="true">
          <el-form-item label="物品名称">
            <el-input v-model="detailSearchParams.materialName" placeholder="请输入物品名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchMaterials">查询</el-button>
            <el-button @click="resetDetailSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="materialList" border style="width: 100%" @selection-change="handleMaterialSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column prop="materialId" label="物品ID" width="280"></el-table-column>
        <el-table-column prop="materialCode" label="物品编号" width="120"></el-table-column>
        <el-table-column prop="materialName" label="物品名称" width="150"></el-table-column>
        <el-table-column prop="modelNumber" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="unit" label="单位" width="80"></el-table-column>
        <el-table-column prop="brand" label="品牌" width="120"></el-table-column>
        <el-table-column prop="purchaseQuantity" label="数量" width="100"></el-table-column>
        <el-table-column prop="price" label="单价" width="100"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectMaterials">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import extendJS from "@/extension/new_qualitytest/inboundtest/Quality_InboundTest.js";
import { ref, reactive, toRefs, defineComponent, onMounted, watch } from "vue";
import http from '@/api/http'
import { ElMessage, ElLoading } from 'element-plus';

    export default defineComponent({
  name: 'Quality_InboundTest',
        setup() {
    // 原始表格配置
            const table = ref({
                key: 'InspectionOrderID',
                footer: "Foots",
                cnName: '到货质检单',
                name: 'inboundtest/Quality_InboundTest',
                url: "/Quality_InboundTest/",
                sortName: "CreateDate"
            });
    const extend = extendJS;
    
    // 表单字段
    const editFormFields = ref({
      "InspectionOrderCode": "",
      "InspectionSubject": "",
      "InspectionDate": "",
      "Inspector": "",
      "Department": "",
      "ContactPhone": "",
      "PurchaseOrderID": "",
      "InspectorRemark": ""
    });
    
    const editFormOptions = ref([
      [
        { "title": "检验单号", "required": true, "field": "InspectionOrderCode" },
        { "title": "检验主题", "required": true, "field": "InspectionSubject" }
      ],
      [
        { "title": "检验日期", "required": true, "field": "InspectionDate" },
        { "title": "检验人", "required": true, "field": "Inspector" }
      ],
      [
        { "title": "所在部门", "required": true, "field": "Department" },
        { "title": "联系方式", "field": "ContactPhone" }
      ],
      [
        { "title": "采购单号外检guid", "field": "PurchaseOrderID" }
      ],
      [
        { "title": " 备注", "field": "InspectorRemark" }
      ]
    ]);
    
    const columns = ref([]);
            const detail = ref({
      cnName: "检验明细",
      table: "InspectionDetail",
                columns: [],
                sortName: "",
      key: "InspectionDetailId"
            });
    
    // 新增功能的数据
    const autoGenerateCode = ref(true);
    const purchaseDialogVisible = ref(false);
    const selectedPurchase = ref(null);
    const searchParams = ref({
      purchaseOrderCode: '',
      supplierId: ''
    });
    
    const purchaseInfo = reactive({
      purchaseOrderCode: '',
      purchaseOrderId: '',
      purchaseDate: null,
      supplierName: '',
      contactPerson: '',
      supplierPhone: '',
      purchaser: '',
      purchaseDepartment: '',
      purchaseContactPhone: '',
    });
    
    const purchaseOrders = ref([]);
    
    // 明细相关
    const detailData = ref([
      
    ]);
    
    const selectedDetails = ref([]);
    
    // 附件相关
    const attachment = ref({
      name: '新建文本文档.PDF',
      size: '0',
      uploadDate: '2022-08-17 14:52:7'
    });
    
    // 在setup函数中添加新的state和方法
    const detailDialogVisible = ref(false);
    const detailSearchParams = ref({
      materialName: '',
      materialCode: ''
    });
    const materialList = ref([]);
    const selectedMaterials = ref([]);
    
    // 监听自动编号复选框变化
    watch(autoGenerateCode, (newVal) => {
      if (newVal === true) {
        // 如果勾选了自动编号，则调用后台获取编号
        getAutoCode();
      }
    });
    
    // 获取自动编号的方法
    const getAutoCode = () => {
      http.get('/api/Quality_InboundTest/getToolCode', null, true)
        .then(res => {
          if (res && res.status) {
            console.log('获取到自动编号:', res.data);
            editFormFields.value.InspectionOrderCode = res.data;
          } else {
            console.error('获取自动编号失败:', res);
            ElMessage.error('获取自动编号失败');
          }
        })
        .catch(err => {
          console.error('获取自动编号异常:', err);
          ElMessage.error('获取自动编号异常');
        });
    };
    
    // 方法
    const openPurchaseOrderDialog = () => {
      purchaseDialogVisible.value = true;
      searchPurchaseOrders();
    };
    
    const searchPurchaseOrders = () => {
      const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 构建查询条件，确保与后端参数格式匹配
      const whereList = [];
      
      // 添加采购单号查询条件（如果有）
      if (searchParams.value.purchaseOrderCode) {
        whereList.push({
          name: "order_no",
          value: searchParams.value.purchaseOrderCode
        });
      }
      
      // 添加供应商ID查询条件（如果有）
      if (searchParams.value.supplierId) {
        whereList.push({
          name: "purchase_supplierid",
          value: searchParams.value.supplierId
        });
      }
      
      http.post('/api/Quality_InboundTest/getPurchaseOrderWithDetails', {
        Page: 1,
        Rows: 30,
        Wheres: JSON.stringify(whereList),
        Sort: 'purchase_date',
        Order: 'desc'
      }, true).then(res => {
        loading.close();
        console.log('采购单API返回数据:', res);
        
        // 处理API返回数据
        let dataRows = [];
        
        if (res && res.rows && Array.isArray(res.rows)) {
          dataRows = res.rows;
        } else if (res && res.data && res.data.rows && Array.isArray(res.data.rows)) {
          dataRows = res.data.rows;
        } else if (res && Array.isArray(res)) {
          dataRows = res;
        }
        
        if (dataRows.length > 0) {
          // 打印原始数据的第一条记录，方便调试
          console.log('原始数据第一条记录:', dataRows[0]);
          
          // 映射数据到前端所需格式，确保字段名与后端返回的一致
          purchaseOrders.value = dataRows.map(item => {
            return {
              id: item.PurchaseOrderId,
              purchaseOrderCode: item.OrderNo,
              orderTitle: item.OrderTitle,
              purchaseDate: item.PurchaseDate,
              supplierName: item.SupplierName || '未知供应商',
              purchaser: item.PurchasePerson || '未知采购员',
              purchaseDepartment: item.PurchaseDept || '未知部门',
              contactPerson: item.ContactPerson || '',
              supplierPhone: item.ContactPhone || '',
              related_project: item.RelatedProject || '',
              status: item.Status || '',
              // 保存供应商和采购人员信息，以便后续使用
              supplierId: item.SupplierId,
              purchaseEmployeeId: item.PurchaseEmployeeId,
              contactMethod: item.ContactMethod,
              // 物品概要
              itemSummary: item.RelatedProject || ''
            };
          });
          console.log('处理后的采购单数据:', purchaseOrders.value);
        } else {
          purchaseOrders.value = [];
          ElMessage.warning('没有找到符合条件的采购单');
        }
      }).catch(err => {
        loading.close();
        console.error('获取采购单列表失败:', err);
        ElMessage.error('获取采购单列表失败: ' + (err.message || '未知错误'));
      });
    };
    
    const resetSearch = () => {
      searchParams.value = {
        purchaseOrderCode: '',
        supplierId: ''
      };
    };
    
    const handlePurchaseSelectionChange = (val) => {
      selectedPurchase.value = val.length > 0 ? val[0] : null;
    };
    
    const handleRowClick = (row) => {
      // 由于没有具体的ref，这里只是概念性的示意
      // this.$refs.purchaseTable.toggleRowSelection(row);
    };
    
    const confirmSelectPurchase = () => {
      if (selectedPurchase.value) {
        console.log('选中的采购单信息:', selectedPurchase.value);
        
        // 将选中的采购单信息填充到表单
        purchaseInfo.purchaseOrderCode = selectedPurchase.value.purchaseOrderCode;
        purchaseInfo.purchaseOrderId = selectedPurchase.value.id;
        
        // 确保采购单ID正确保存到表单中，使用与后端一致的字段名
        editFormFields.value.PurchaseOrderID = selectedPurchase.value.id; 
        
        purchaseInfo.purchaseDate = selectedPurchase.value.purchaseDate;
        
        // 填充供应商信息
        purchaseInfo.supplierName = selectedPurchase.value.supplierName;
        purchaseInfo.contactPerson = selectedPurchase.value.contactPerson;
        purchaseInfo.supplierPhone = selectedPurchase.value.supplierPhone;
        
        // 填充采购人员信息
        purchaseInfo.purchaser = selectedPurchase.value.purchaser;
        purchaseInfo.purchaseDepartment = selectedPurchase.value.purchaseDepartment;
        purchaseInfo.purchaseContactPhone = selectedPurchase.value.contactMethod;
        
        // 关闭弹窗
        purchaseDialogVisible.value = false;
        
        console.log('已选择采购单并填充数据:', purchaseInfo);
        console.log('表单字段:', editFormFields.value);
        
        // 选择采购单后，可以立即加载相关的物料明细
        if (detailData.value.length === 0) {
          ElMessage.info('正在加载采购单相关物料...');
          searchMaterials();
        }
      } else {
        ElMessage.warning('请选择一个采购单');
      }
    };
    
    const handleSelectionChange = (val) => {
      selectedDetails.value = val;
    };
    
    const addDetail = () => {
      // 打开明细选择弹窗
      detailDialogVisible.value = true;
      
      // 不再使用本地示例数据，直接调用API获取实际数据
      searchMaterials();
    };
    
    const editDetail = (row) => {
      // 编辑明细的逻辑
    };
    
    const removeDetail = (row) => {
      const index = detailData.value.indexOf(row);
      if (index !== -1) {
        detailData.value.splice(index, 1);
      }
    };
    
    const removeSelected = () => {
      // 移除选中项
      if (selectedDetails.value.length === 0) {
        return;
      }
      
      const idsToRemove = selectedDetails.value.map(item => item.materialCode);
      detailData.value = detailData.value.filter(item => !idsToRemove.includes(item.materialCode));
    };
    
    const fileChange = (file) => {
      // 文件变更逻辑
      console.log('文件变更', file);
      
      // 确保file对象存在且包含raw属性
      if (!file || !file.raw) {
        console.error('文件对象无效');
        return;
      }
      
      // 格式化文件大小
      const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
      };
      
      // 获取当前时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      
      // 格式化时间
      const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      
      // 更新附件信息
      attachment.value = {
        name: file.raw.name,
        size: formatFileSize(file.raw.size),
        uploadDate: formattedTime,
        file: file.raw,
        // 保存文件对象，用于后续上传
        fileObject: file.raw
      };
      
      // 输出日志，便于调试
      console.log('附件信息已更新:', attachment.value);
    };
    
    const reuploadFile = () => {
      // 重新上传逻辑
      attachment.value = null;
      console.log('附件已清空，可重新上传');
      ElMessage.success('请重新选择文件上传');
    };
    
    const deleteFile = () => {
      // 删除文件
      attachment.value = null;
      ElMessage.success('附件已删除');
      console.log('附件已删除');
    };
    
    const saveWithAttachment = () => {
      // 如果有附件，先上传附件
      if (attachment.value && attachment.value.fileObject) {
        const formData = new FormData();
        formData.append('fileInput', attachment.value.fileObject);
        
        const loading = ElLoading.service({
          lock: true,
          text: '上传附件中...',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 调用上传API
        http.post('/api/Quality_InboundTest/UploadFile', formData, true)
          .then(res => {
            loading.close();
            if (res.status) {
              // 上传成功后保存表单
              ElMessage.success('附件上传成功');
              // 更新附件路径
              attachment.value.path = res.data;
              // 继续保存表单
              save();
            } else {
              ElMessage.error(res.message || '附件上传失败');
            }
          })
          .catch(err => {
            loading.close();
            console.error('附件上传失败:', err);
            ElMessage.error('附件上传失败: ' + (err.message || '未知错误'));
          });
      } else {
        // 没有附件，直接保存表单
        save();
      }
    };
    
    const save = () => {
      // 表单验证
      if (!editFormFields.value.InspectionSubject) {
        ElMessage.warning('请输入检验主题');
        return;
      }
      if (!editFormFields.value.InspectionOrderCode) {
        ElMessage.warning('请输入检验单号');
        return;
      }
      if (!editFormFields.value.InspectionDate) {
        ElMessage.warning('请选择检验日期');
        return;
      }
      if (!editFormFields.value.Inspector) {
        ElMessage.warning('请选择检验人员');
        return;
      }
      if (!editFormFields.value.Department) {
        ElMessage.warning('请选择所在部门');
        return;
      }
      
      // 验证采购单是否已选择
      if (!purchaseInfo.purchaseOrderId) {
        ElMessage.warning('请选择采购单');
        return;
      }
      
      // 如果没有明细数据，提示用户
      if (!detailData.value || detailData.value.length === 0) {
        ElMessage.warning('请添加检验明细');
        return;
      }
      
      // 构建保存数据 - 使用标准SaveModel格式
      const saveModel = {
        MainData: {
        // ... 现有字段 ...
        
        // 添加附件信息
        AttachmentPath: attachment.value ? attachment.value.path : null,
        AttachmentName: attachment.value ? attachment.value.name : null,
        

          InspectionOrderID: "00000000-0000-0000-0000-000000000000", // 使用空GUID而不是null
          InspectionOrderCode: editFormFields.value.InspectionOrderCode || "AUTO" + new Date().getTime(), // 确保有值
          InspectionSubject: editFormFields.value.InspectionSubject || "到货质检-" + new Date().toLocaleDateString(), // 确保有值
          // 日期格式调整为YYYY-MM-DD格式，符合后台date类型
          InspectionDate: editFormFields.value.InspectionDate ? 
                          new Date(editFormFields.value.InspectionDate).toISOString().split('T')[0] : 
                          new Date().toISOString().split('T')[0],
          Inspector: editFormFields.value.Inspector || "admin", // 确保有值
          Department: editFormFields.value.Department || "质检部", // 确保有值
          ContactPhone: editFormFields.value.ContactPhone || "", 
          // PurchaseOrderID在后台是可空的Guid类型
          PurchaseOrderID: purchaseInfo.purchaseOrderId || null,
          InspectorRemark: editFormFields.value.InspectorRemark || "",
          
          // 审计字段设置为null，由后端自动填充
          CreateID: null,
          Creator: null,
          CreateDate: null,
          ModifyID: null,
          Modifier: null,
          ModifyDate: null
        },
        
        // SaveModel标准格式需要提供一个TableName字段
        TableName: "Quality_InboundTest",
        
        // 明细表数据 - 确保字段顺序与后端表结构完全匹配
        DetailData: detailData.value.map(item => ({
          InspectionDetailID: "00000000-0000-0000-0000-000000000000",
          InspectionOrderID: "00000000-0000-0000-0000-000000000000",
          MaterialId: item.materialId || "00000000-0000-0000-0000-000000000000",
          MaterialCode: item.materialCode || "无编码",
          MaterialName: item.materialName || "未命名物料",
          MaterialType: "成品",
          MaterialModel: item.modelNumber || "",
          UnitName: item.unit || "个",
          Brand: item.brand || "",
          PurchaseUnitPrice: parseFloat(item.purchaseUnitPrice || 0).toFixed(2), // 转为decimal(10,2)类型
          SalePrice: parseFloat(item.salePrice || 0).toFixed(2), // 转为decimal(10,2)类型
          InspectionType: item.inspectionType || "免检",
          ReceivedQuantity: typeof item.receivedQuantity === 'string' ? 0 : parseInt(item.receivedQuantity) || 0,
          InspectedQuantity: typeof item.inspectionQuantity === 'string' ? 0 : parseInt(item.inspectionQuantity) || 0, 
          QualifiedQuantity: typeof item.qualifiedQuantity === 'string' ? 0 : parseInt(item.qualifiedQuantity) || 0,
          StockableQuantity: typeof item.warehouseQuantity === 'string' ? 0 : parseInt(item.warehouseQuantity) || 0, 
          ReturnQuantity: typeof item.returnQuantity === 'string' ? 0 : parseInt(item.returnQuantity) || 0,
          InspectionDetailRemark: "55646464", 
          CreateID: null,
          Creator: null,
          CreateDate: null,
          ModifyID: null,
          Modifier: null,
          ModifyDate: null
        })),
        
        // Extra字段 - 确保是一个JSON字符串
        Extra: JSON.stringify({ 
          Table1List: detailData.value.map(item => ({
            // 确保字段顺序和名称与后端映射完全一致
            InspectionDetailID: "00000000-0000-0000-0000-000000000000",
            InspectionOrderID: "00000000-0000-0000-0000-000000000000",
            MaterialId: item.materialId || "00000000-0000-0000-0000-000000000000", // 确保传递正确的materialId
            MaterialCode: item.materialCode || "无编码",
            MaterialName: item.materialName || "未命名物料",
            MaterialType: "成品",
            MaterialModel: item.modelNumber || "",            
            UnitName: item.unit || "个",
            Brand: item.brand || "",
            PurchaseUnitPrice: parseFloat(item.purchaseUnitPrice || 0).toFixed(2), // 转为decimal(10,2)类型
            SalePrice: parseFloat(item.salePrice || 0).toFixed(2), // 转为decimal(10,2)类型
            ReturnQuantity: typeof item.returnQuantity === 'string' ? 0 : parseInt(item.returnQuantity) || 0,
            StockableQuantity: typeof item.warehouseQuantity === 'string' ? 0 : parseInt(item.warehouseQuantity) || 0, 
            QualifiedQuantity: typeof item.qualifiedQuantity === 'string' ? 0 : parseInt(item.qualifiedQuantity) || 0,
            InspectionDetailRemark:"55646464", 
            InspectedQuantity: typeof item.inspectionQuantity === 'string' ? 0 : parseInt(item.inspectionQuantity) || 0,
            InspectionType: item.inspectionType || "免检",
            ReceivedQuantity: typeof item.receivedQuantity === 'string' ? 0 : parseInt(item.receivedQuantity) || 0
          }))
        })
      };
      
      console.log('发送到后端的数据:', JSON.stringify(saveModel));
      
      const loading = ElLoading.service({
        lock: true,
        text: '保存中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 调用保存API
      http.post('/api/Quality_InboundTest/Add', saveModel, true)
        .then(res => {
          loading.close();
          if (res.status) {
            ElMessage.success('保存成功');
            // 修改这里的跳转逻辑
            setTimeout(() => {
              // 跳转到Show_InboundTest.vue列表页面
              window.location.href = '#/new_qualitytest/inboundtest/Show_InboundTest';
            }, 1500);
          } else {
            ElMessage.error(res.message || '保存失败');
          }
        })
        .catch(err => {
          loading.close();
          console.error('保存失败:', err);
          ElMessage.error('保存失败：请确认后端API接口是否正确');
        });
    };
    
    const cancel = () => {
      // 取消操作
      console.log('取消操作');
    };
    
    const searchMaterials = () => {
      const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 如果还没有选择采购单，提示用户先选择采购单
      if (!purchaseInfo.purchaseOrderId) {
        loading.close();
        ElMessage.warning('请先选择采购单');
        detailDialogVisible.value = false;
        return;
      }
      
      // 为调试目的，打印当前采购单ID
      console.log('当前采购单ID:', purchaseInfo.purchaseOrderId);
      
      // 构建请求参数，确保与后端期望的格式一致
      const whereList = [{
        name: 'value',
        value: purchaseInfo.purchaseOrderId.toString()
      }];
      
      const loadData = {
        Page: 1,
        Rows: 30,
        // 确保Value字段与后端期望的一致
        Value: purchaseInfo.purchaseOrderId.toString(),
        Wheres: JSON.stringify(whereList)
      };
      
      console.log('发送到后端的参数:', loadData);
      
      // 调用API获取物品表数据
      http.post('/api/Quality_InboundTest/getTable1Data', loadData, true).then(res => {
        loading.close();
        console.log('物品表API返回数据:', res);
        
        // 处理API返回数据
        let dataRows = [];
        
        if (res && res.rows && Array.isArray(res.rows)) {
          dataRows = res.rows;
        } else if (res && res.data && res.data.rows && Array.isArray(res.data.rows)) {
          dataRows = res.data.rows;
        } else if (res && Array.isArray(res)) {
          dataRows = res;
        }
        
        console.log('解析后的数据行:', dataRows);
        
        if (dataRows.length > 0) {
          // 打印第一条记录的所有字段，便于调试
          console.log('第一条记录所有字段:', dataRows[0]);
          
          // 检查是否包含MaterialId字段
          const firstItem = dataRows[0];
          const hasUpperCaseId = 'MaterialId' in firstItem;
          const hasLowerCaseId = 'material_id' in firstItem;
          const hasId = 'id' in firstItem;
          
          console.log('是否包含MaterialId字段:', hasUpperCaseId);
          console.log('是否包含material_id字段:', hasLowerCaseId);
          console.log('是否包含id字段:', hasId);
          
          // 映射数据到前端所需格式
          materialList.value = dataRows.map(item => {
            const materialId = item.MaterialId || item.material_id || item.id || '';
            console.log('处理物料ID:', materialId);
            
            return {
              materialId: materialId,
              materialCode: item.MaterialCode || item.material_code || '',
              materialName: item.MaterialName || item.material_name || '',
              modelNumber: item.MaterialModel || item.model_number || '',
              unit: item.UnitName || item.unit_name || '个',
              brand: item.Brand || item.brand || '',
              purchaseQuantity: item.PurchaseUnitQuantity || item.purchase_quantity || 0,
              price: item.PurchaseUnitPrice || item.price || 0,
              salePrice: item.SalePrice || item.sale_price || 0
            };
          });
          
          console.log('处理后的物料列表:', materialList.value);
        } else {
          materialList.value = [];
          ElMessage.warning('没有找到相关物品数据');
          
          // 尝试使用另一个API获取数据
          tryAlternativeDataSource();
        }
      }).catch(err => {
        loading.close();
        console.error('获取物品数据失败:', err);
        ElMessage.error('获取物品数据失败: ' + (err.message || '未知错误'));
        
        // 尝试使用另一个API获取数据
        tryAlternativeDataSource();
      });
    };
    
    // 尝试使用替代数据源获取材料数据
    const tryAlternativeDataSource = () => {
      // 不显示加载状态，因为这是一个后备方法
      console.log('正在尝试替代数据源获取材料信息');
      
      // 尝试另一个API路径
      http.post('/api/MaterialMaster/GetPageData', {
        page: 1,
        rows: 10,
        sort: 'CreateDate',
        order: 'desc'
      }, true).then(res => {
        console.log('替代API返回数据:', res);
        
        // 处理API返回数据
        let dataRows = [];
        
        if (res && res.rows && Array.isArray(res.rows)) {
          dataRows = res.rows;
        } else if (res && res.data && res.data.rows && Array.isArray(res.data.rows)) {
          dataRows = res.data.rows;
        } else if (res && Array.isArray(res)) {
          dataRows = res;
        }
        
        if (dataRows.length > 0) {
          // 打印第一条记录，便于调试
          console.log('替代API第一条记录:', dataRows[0]);
          
          // 检查是否包含MaterialId字段
          const firstItem = dataRows[0];
          const hasUpperCaseId = 'MaterialId' in firstItem;
          const hasLowerCaseId = 'material_id' in firstItem;
          const hasId = 'id' in firstItem;
          
          console.log('替代API是否包含MaterialId字段:', hasUpperCaseId);
          console.log('替代API是否包含material_id字段:', hasLowerCaseId);
          console.log('替代API是否包含id字段:', hasId);
          
          // 映射数据到前端所需格式
          materialList.value = dataRows.map(item => {
            const materialId = item.MaterialId || item.material_id || item.id || '';
            console.log('处理物料ID:', materialId);
            
            return {
              materialId: materialId,
              materialCode: item.MaterialCode || item.material_code || '',
              materialName: item.MaterialName || item.material_name || '',
              modelNumber: item.MaterialModel || item.model_number || '',
              unit: item.UnitName || item.unit_name || '个',
              brand: item.Brand || item.brand || '',
              purchaseQuantity: item.PurchaseUnitQuantity || item.purchase_quantity || 0,
              price: item.PurchaseUnitPrice || item.price || 0,
              salePrice: item.SalePrice || item.sale_price || 0
            };
          });
          
          console.log('处理后的物料列表:', materialList.value);
        } else {
          materialList.value = [];
          ElMessage.warning('无法获取物料数据，请联系管理员');
        }
      }).catch(err => {
        console.error('获取替代物品数据失败:', err);
        ElMessage.error('所有获取物品数据的方法都失败，请联系管理员');
      });
    };
    
    const resetDetailSearch = () => {
      detailSearchParams.value = {
        materialName: '',
        materialCode: ''
      };
    };
    
    const handleMaterialSelectionChange = (val) => {
      selectedMaterials.value = val;
    };
    
    const confirmSelectMaterials = () => {
      if (selectedMaterials.value && selectedMaterials.value.length > 0) {
        console.log('选中的物料:', selectedMaterials.value);
        
        // 将选中的物料添加到明细表格中
        selectedMaterials.value.forEach(material => {
          // 检查是否已存在相同物料
          const existingMaterial = detailData.value.find(item => 
            item.materialId === material.materialId // 使用materialId作为唯一标识
          );
          
          if (!existingMaterial) {
            // 打印每个物料的ID，便于调试
            console.log('添加物料，ID为:', material.materialId);
            
            detailData.value.push({
              materialId: material.materialId, // 确保包含materialId字段
              materialCode: material.materialCode,
              materialName: material.materialName,
              modelNumber: material.modelNumber,
              unit: material.unit,
              brand: material.brand,
              purchaseQuantity: material.purchaseQuantity || 0,
              purchaseUnitPrice: material.price || 0, // 确保包含采购单价
              salePrice: material.salePrice || 0, // 确保包含销售单价
              inspectionType: '免检', // 默认检验类型
              receivedQuantity: material.purchaseQuantity || 0, // 默认收货数量等于采购数量
              inspectionQuantity: material.purchaseQuantity || 0, // 默认检验数量等于采购数量
              qualifiedQuantity: material.purchaseQuantity || 0, // 默认合格数量等于采购数量
              defectQuantity: 0, // 默认不良品数量为0
              warehouseQuantity: material.purchaseQuantity || 0, // 默认入库数量等于采购数量
              returnQuantity: 0, // 默认退货数量为0
              remark: ''  // 默认备注为空
            });
          }
        });
        
        // 关闭弹窗
        detailDialogVisible.value = false;
        ElMessage.success(`已添加${selectedMaterials.value.length}个物料到明细`);
      } else {
        ElMessage.warning('请至少选择一个物料');
      }
    };
    
    onMounted(() => {
      if (extend.onInited) {
        extend.onInited();
      }
      
      // 如果默认勾选了自动编号，则获取编号
      if (autoGenerateCode.value) {
        getAutoCode();
      }
    });
    
            return {
                table,
                extend,
                editFormFields,
                editFormOptions,
                columns,
                detail,
      autoGenerateCode,
      purchaseDialogVisible,
      selectedPurchase,
      searchParams,
      purchaseInfo,
      purchaseOrders,
      detailData,
      selectedDetails,
      attachment,
      openPurchaseOrderDialog,
      searchPurchaseOrders,
      resetSearch,
      handlePurchaseSelectionChange,
      handleRowClick,
      confirmSelectPurchase,
      handleSelectionChange,
      addDetail,
      editDetail,
      removeDetail,
      removeSelected,
      fileChange,
      reuploadFile,
      deleteFile,
      saveWithAttachment,
      cancel,
      detailDialogVisible,
      detailSearchParams,
      materialList,
      selectedMaterials,
      searchMaterials,
      resetDetailSearch,
      handleMaterialSelectionChange,
      confirmSelectMaterials
            };
  }
    });
</script>

<style scoped>
.inspection-container {
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  position: relative;
  padding-left: 10px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 14px;
  background-color: #409EFF;
}

.form-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.form-row {
  display: flex;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.form-item:last-child {
  margin-right: 0;
}

.form-item-full {
  width: 100%;
  display: flex;
  align-items: flex-start;
}

.label {
  width: 80px;
  text-align: right;
  padding-right: 12px;
  color: #606266;
  font-size: 14px;
}

.required .label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.inspection-detail-section {
  margin-bottom: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: bold;
}

.detail-buttons {
  display: flex;
  gap: 10px;
}

.attachment-section {
  margin-bottom: 20px;
}

.upload-area {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.existing-file {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.file-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.delete-btn {
  color: #F56C6C;
}

.search-bar {
  margin-bottom: 20px;
}

:deep(.el-textarea__inner) {
  font-family: Arial, sans-serif;
}
</style>
